package com.yhd.service.impl;

import com.yhd.entity.TCorporate;
import com.yhd.entity.TCycleImg;
import com.yhd.entity.dto.CycleImgDto;
import com.yhd.entity.dto.TCorporateDto;
import com.yhd.entity.dto.UserDto;
import com.yhd.entity.query.CorporateVO;
import com.yhd.mapper.CorporateMapper;
import com.yhd.service.CorporateService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

@Transactional(rollbackFor = Exception.class)
@Service
public class CorporateServiceImpl implements CorporateService {
	@Autowired
	private CorporateMapper corporateMapper;
	
	@Override
	public TCorporate getInfo() {
		List<TCorporate> tCorporates = corporateMapper.select(new TCorporate());
		if (!CollectionUtils.isEmpty(tCorporates)) {
			return tCorporates.get(0);
		}
		return null;
	}
	
	@Override
	public TCorporateDto ourInfo() {
		TCorporateDto result = new TCorporateDto();
		TCorporate tCorporate = getInfo();
		if (null != tCorporate){
			BeanUtils.copyProperties(tCorporate, result);
			return result;
		}
		return null;
	}

	@Override
	public TCorporateDto putCorporate(CorporateVO corporateVO, UserDto userInfo) {
		if (null != corporateVO){
			if (null != corporateVO.getId()){
				//修改
				TCorporate tCorporate = new TCorporate();
				BeanUtils.copyProperties(corporateVO,tCorporate);
				tCorporate.setUpdateDate(new Date());
				tCorporate.setUpdateUserId(userInfo.getId());
				int updateCycleImg = corporateMapper.updateByPrimaryKeySelective(tCorporate);
				if (updateCycleImg > 0){
					TCorporateDto tCorporateDto = new TCorporateDto();
					BeanUtils.copyProperties(tCorporate,tCorporateDto);
					return tCorporateDto;
				}
			}else {
				//新增
				TCorporate tCorporate = new TCorporate();
				BeanUtils.copyProperties(corporateVO,tCorporate);
				tCorporate.setCreateDate(new Date());
				tCorporate.setCreateUserId(userInfo.getId());
				tCorporate.setUpdateDate(new Date());
				tCorporate.setUpdateUserId(userInfo.getId());
				int insertCorporate = corporateMapper.insert(tCorporate);
				if (insertCorporate > 0){
					TCorporateDto tCorporateDto = new TCorporateDto();
					BeanUtils.copyProperties(tCorporate,tCorporateDto);
					return tCorporateDto;
				}
			}
		}
		return null;
	}

	@Override
	public boolean deleteCorporate(CorporateVO corporateVO) {
		if (null != corporateVO && null != corporateVO.getId()) {
			TCorporate tCorporate = new TCorporate();
			tCorporate.setId(corporateVO.getId());
			int deleteCycleImg = corporateMapper.delete(tCorporate);
			if (deleteCycleImg > 0) {
				return true;
			}
		}
		return false;
	}
}
